package com.dev.happy.handler;

import com.dev.happy.common.CommonResult;
import com.dev.happy.validation.exception.CustomViolationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 异常统一处理器
 *
 * @author caonuoqi
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public CommonResult handleException(Exception exception) {
         if (exception instanceof ConstraintViolationException) {
            ConstraintViolationException e = (ConstraintViolationException) exception;
            Set<ConstraintViolation<?>> errSet = e.getConstraintViolations();
            String errMsg = errSet.stream().map(x -> x.getMessageTemplate()).collect(Collectors.joining(";"));
            return CommonResult.failure(errMsg);
        } else if (exception instanceof CustomViolationException) {
            return CommonResult.failure(exception.getMessage());
        }
        return CommonResult.failure(String.format("系统异常，请联系管理员:%s",exception.getMessage()));
    }
}
